package co.fitstart.admin.web.controller.report;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.admin.entity.report.ReportPrepare;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.ReportService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.report.VisitorReport;
import co.fitstart.entity.site.Site;

@Controller
@RequestMapping("/visitor-reports")
@MenuSetting("menu-report")
public class VisitorReportController {
    
    @Autowired
    private SiteService siteService;
    
    @Autowired
    private ReportService reportService;
    
    @Autowired
    private PrincipalService principalService;
    
    private static final Logger logger = LoggerFactory.getLogger(VisitorReportController.class);
    
    /**
     * 
     * @param login
     * @param siteId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-visitor-report")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(name = "site", required = false) Long siteId,
                             @RequestParam(name = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                             @RequestParam(name = "period", required = false, defaultValue = "day") String period) {
        
        ModelAndView modelAndView = new ModelAndView("report/visitor-report-list");
        
        Site site = null;
        if(!login.hasSite() && siteId != null) {
            site = siteService.load(siteId);
        }else if (login.hasSite()){
            site = login.getSite();
        }
        
        ReportPrepare reportPrepare = new ReportPrepare(site, date, period);
        modelAndView.addAllObjects(reportPrepare.describeReport());
        
        Map<String, VisitorReport> reports = new HashMap<>();
        
        if(site == null && (login.isAreaManager() || login.isAreaServer())) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                reports = reportService.listVisitorReport(sites, reportPrepare.getCurrentDate(), period);
            }
        } else {
            reports = reportService.listVisitorReport(site, reportPrepare.getCurrentDate(), period);
        }
        
        modelAndView.addObject("reports", reports);
        
        VisitorReport statistics = reportService.getVisitorReportStatistics(reports);
        modelAndView.addObject("statistics", statistics);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param siteId
     * @param date
     * @return
     */
    @RequestMapping(value = "/visit-record", method = RequestMethod.GET)
    public ModelAndView editVisitRecord(@RequestParam("site") Long siteId,
                                       @RequestParam("date") String date) {
        
        ModelAndView modelAndView = new ModelAndView("report/visitor-report-edit");
        
        modelAndView.addObject("site", siteId);
        modelAndView.addObject("date", date);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param visitorReport
     * @return
     */
    @RequestMapping(value = "/visit-record", method = RequestMethod.PATCH)
    public @ResponseBody String onEditVisitRecord(@RequestParam("site") Long siteId,
                                                  @RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                                                  @RequestParam("visitAmount") long visitAmount) {
        
        Result result = new Result();
        
        try {
            
            Site site = siteService.load(siteId);
            
            reportService.editVisitAmount(site, date, visitAmount);
            
            result.success().message("编辑访客数成功");
            
        } catch (Exception e) {
            
            result.fail().message("编辑访客数失败");
            
            logger.error("#onEditVisitRecord() error ", e);
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    public ModelAndView export() {
        
        ModelAndView modelAndView = new ModelAndView("report/visitor-report-export");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param view
     * @param siteId
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "site") Long siteId,
                                 @RequestParam(value = "beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                 @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("visitor-report.xls"));
        
        // get site
        Site site = siteService.load(siteId);
        modelAndView.addObject("site", site);
        
        VisitorReport visitorReport = reportService.getVisitorReport(site, beginDate, endDate);
        modelAndView.addObject("visitorReport", visitorReport);
        
        List<VisitorReport> reports = reportService.listVisitorReport(site, beginDate, endDate);
        modelAndView.addObject("reports", reports);
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }

}
